# encoding:gbk
'''
'''
import pandas as pd
import numpy as np
import talib
import requests
from collections import OrderedDict
from datetime import datetime
from datetime import time as dt_time
import json
import os
from datetime import datetime, timedelta


def read_from_file(filename):
    if not os.path.exists(filename):
        return ''
    with open(filename, 'r') as file:
        return file.read()

def init(ContextInfo):
    print('已清空今天的交易记录（初始化）')
    ContextInfo.set_universe(['000300.SH'])
    ContextInfo.modeshow = False
    # ContextInfo.accID = '620000002199'

    ContextInfo.poolDate = ""
    dates = requests.get('https://kesyn-1302292689.cos.ap-beijing.myqcloud.com/dates.txt').text.replace('\r', '').split(
        '\n')
    ContextInfo.date_dict = {date: previous_date for previous_date, date in zip(dates, dates[1:])}
    ContextInfo.max_size = 1
    ContextInfo.stocks = {}
    ContextInfo.highest_prices = {}
    directory_path = "C:\\quant\\cache\\"
    ContextInfo.AccId = '170000286930'  # 初始化一个空集合来存储今天已经下单过的股票
    # ContextInfo.AccId = '620000002199'
    ContextInfo.accID = ContextInfo.AccId
    ContextInfo.tradedict = {}
    # ContextInfo.AccId = '620000002199'
    print('启动中')
    ContextInfo.set_account(ContextInfo.AccId)
    # Check if the directory exists
    if not os.path.exists(directory_path):
        # If not, create the directory
        os.makedirs(directory_path)


def get_ext(code):
    code = str(code)
    if code == "000300":
        return ".SH"
    if code == "000001":
        return ".SH"
    if code == "399001":
        return ".SZ"
    if "." in code:
        return ""
    if code > '500000':
        return ".SH"
    else:
        return ".SZ"


def query_info(ContextInfo):
    orders = get_trade_detail_data(ContextInfo.AccId, 'stock', 'order')

    deals = get_trade_detail_data(ContextInfo.AccId, 'stock', 'deal')
    positions = get_trade_detail_data(ContextInfo.AccId, 'stock', 'position')
    accounts = get_trade_detail_data(ContextInfo.AccId, 'stock', 'account')
    return orders, deals, positions, accounts

def one_day_sell(ContextInfo):
    orders, deals, positions, accounts = query_info(ContextInfo)
    size = len(positions)
    if size == 0:
        log(ContextInfo, "空仓")
    else:
        print(positions)
        for position in positions:
            stockData = ContextInfo.get_instrumentdetail(
                position.m_strInstrumentID + get_ext(position.m_strInstrumentID))
            dep = stockData['DownStopPrice']

            order_target_value(position.m_strInstrumentID + get_ext(position.m_strInstrumentID), 0, 'BUY5', ContextInfo,
                               ContextInfo.AccId)


def convertlocaldata(original_data, stock_code):
    print(original_data)
    print(stock_code)
    processed_data = {}
    # 按照 timetag 排序
    sorted_keys = sorted(original_data.keys())

    # 提取并排序 close 值
    sorted_close_values = [original_data[k]['close'] for k in sorted_keys]
    sorted_high_values = [original_data[k]['high'] for k in sorted_keys]
    sorted_low_values = [original_data[k]['low'] for k in sorted_keys]
    sorted_open_values = [original_data[k]['open'] for k in sorted_keys]
    sorted_amount_values = [original_data[k]['amount'] for k in sorted_keys]
    sorted_volume_values = [original_data[k]['volume'] for k in sorted_keys]
    # 将处理后的数据存入新的字典
    processed_data[stock_code] = {'close': sorted_close_values, 'amount': sorted_amount_values,
                                  'volume': sorted_volume_values, 'high': sorted_high_values, 'low': sorted_low_values,
                                  'open': sorted_open_values}
    return processed_data


def log(ContextInfo, data):
    print(f"{ContextInfo.date} {ContextInfo.time}")
    print(data)


def handlebar(ContextInfo):
    index = ContextInfo.barpos
    t = ContextInfo.get_bar_timetag(index)
    date = timetag_to_datetime(t, '%Y-%m-%d')
    time = timetag_to_datetime(t, '%H:%M')
    timestr = time.replace(':', '.')
    ContextInfo.date = date
    ContextInfo.time = time

    if ContextInfo.do_back_test:
        ContextInfo.time = time
    else:
        print(date + ' ' + time)
        if not ContextInfo.is_last_bar():  # and current_date_str == date:
            if not ContextInfo.modeshow:
                ContextInfo.modeshow = True
                print('实盘模式')
            return

    now = datetime.now()
    current_date_str = now.strftime('%Y-%m-%d')

    if time != '14:30':
        return

    # ContextInfo.poolDate = date
    today = date
    print(date)
    print(ContextInfo.date_dict)
    previous_date = ContextInfo.date_dict.get(date)
    two_date = ContextInfo.date_dict.get(previous_date)
    three_date = ContextInfo.date_dict.get(two_date)
    if previous_date is None:
        print("previous date is none")
        return
    log(ContextInfo, "ready to read wencai and buy data")

    wencai_data = ['000300']
    buynext_filename = f'D:\\quant\\buy_ind\\{previous_date}.txt'
    buynext_raw_data = read_from_file(buynext_filename).split('\n')

    sellnext_filename = f'D:\\quant\\sell_ind\\{previous_date}.txt'
    sellnext_raw_data = read_from_file(sellnext_filename).split('\n')

    buynext_data = {data.split(',')[0]: (float(data.split(',')[1]), float(data.split(',')[2])) for data in
                    buynext_raw_data if len(data.split(',')) >= 2}
    sellnext_data = {data.split(',')[0]: (float(data.split(',')[1]), float(data.split(',')[2])) for data in
                     sellnext_raw_data if len(data.split(',')) >= 2}
    ContextInfo.stocks = OrderedDict((stock, buynext_data[stock]) for stock in wencai_data if stock in buynext_data)
    ContextInfo.sellTargetStocks = {stock: sellnext_data[stock][0] for stock in wencai_data if stock in sellnext_data}

    listItems = ContextInfo.stocks.items()
    sellItems = ContextInfo.sellTargetStocks.items()

    stock = '000300'
    buy_price = 0

    for st, (bp, sc) in listItems:
        if st == stock:
            buy_price = bp

    if buy_price == 0:
        return


    sell_price = 0
    for st, sp in sellItems:
        if st == stock:
            sell_price = sp
    if sell_price == 0:
        return

    cash = get_trade_detail_data(ContextInfo.AccId, 'STOCK', 'ACCOUNT')[0].m_dAvailable
    if cash < 0:
        return
    print('get minutes data')
    price = ContextInfo.get_market_data_ex(fields=['close', 'open', 'high', 'low', 'volume'],
                                           stock_code=[stock + get_ext(stock)], period='1m',
                                           start_time=timetag_to_datetime(t, '%Y%m%d093000'),
                                           end_time=timetag_to_datetime(t, '%Y%m%d%H%M%S'), count=10,
                                           dividend_type='front', fill_data=True,
                                           subscribe=not ContextInfo.do_back_test)
    print('minutes data got')
    print('get daily data')
    price_daily = ContextInfo.get_market_data_ex(fields=['close', 'high', 'open', 'low', 'volume'],
                                                 stock_code=[stock + get_ext(stock)], period='1d',
                                                 end_time=timetag_to_datetime(t, '%Y%m%d%H%M%S'), count=60,
                                                 dividend_type='front', fill_data=True,
                                                 subscribe=not ContextInfo.do_back_test)

    currentbar = price[stock + get_ext(stock)]
    current_price = currentbar['close'][-1]
    price_daily[stock + get_ext(stock)]['close'][-1] = current_price

    if cash > 500:
        if current_price > buy_price:
            passorder(23, 1102, ContextInfo.AccId, "510300.SH", 0, -1, cash, 'HULL', 2,
                    ContextInfo)

    if cash <= 500:
        if current_price < sell_price:
            order_target_value(stock + get_ext(stock), "510300.SH", 'BUY5', ContextInfo,
                               ContextInfo.AccId)
